package app.framework.freemarker.util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * <p>
 * JS 脚本工具类。
 * </p>
 *
 * @author mh.z
 */
public class EcmaScriptUtil {
    private static final Pattern SOURCE_CODE_START_PATTERN;
    private static final Pattern SOURCE_CODE_END_PATTERN;

    static {
        SOURCE_CODE_START_PATTERN = Pattern.compile("\\/\\*\\s*SOURCE-CODE-START\\s*\\*\\/");
        SOURCE_CODE_END_PATTERN = Pattern.compile("\\/\\*\\s*SOURCE-CODE-END\\s*\\*\\/");
    }

    /**
     * 返回源代码开始的索引
     *
     * @param source
     * @return
     */
    public static int getSourceStartIndex(String source) {
        if (source == null) {
            return 0;
        }

        Matcher matcher = SOURCE_CODE_START_PATTERN.matcher(source);
        if (!matcher.find()) {
            return 0;
        }

        int index = matcher.start();
        index = source.indexOf("*/", index);
        index = index + 2;

        return index;
    }

    /**
     * 返回源代码结束的索引
     *
     * @param source
     * @return
     */
    public static int getSourceEndIndex(String source) {
        if (source == null) {
            return 0;
        }

        Matcher matcher = SOURCE_CODE_END_PATTERN.matcher(source);
        if (!matcher.find()) {
            return source.length();
        }

        int index = matcher.start();

        return index;
    }

}
